//
//  VVTextView.swift
//  Weibo
//
//  Created by 王惠平 on 2017/4/5.
//  Copyright © 2017年 Will Wang. All rights reserved.
//

import UIKit

class VVTextView: UITextView {

    //占位label
    private lazy var placeHolderLabel: UILabel = {
    
        let label = UILabel()
        
        label.text = "请输入内容"
    
        label.textColor = UIColor.lightGray
        
        label.font = UIFont.systemFont(ofSize: 14)
        
        //多行显示
        label.numberOfLines = 0
    
        return label
        
    }()
    
    //占位文字
    var placeHolder: String? {
        
        didSet {
            
            placeHolderLabel.text = placeHolder
            
        }
        
        
    }
    
   override var font: UIFont? {
        
        didSet {
            
            if font != nil {
                
                placeHolderLabel.font = font
            }
        }
    }
    
    //测试用
//    override var text: String! {
//        
//        didSet {
//            
//            //判断hasText表示文本框是否有内容 有内容就隐藏
//            placeHolderLabel.isHidden = self.hasText
//            
//        }
//    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        
        super.init(frame: frame, textContainer: textContainer)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    fileprivate func setupUI() {
        
        //不能代理,因为外界按钮的判断设置了代理,会把你再设置的代理覆盖掉,使用通知监听文字的改变
        NotificationCenter.default.addObserver(self, selector: #selector(textChange), name: NSNotification.Name.UITextViewTextDidChange, object: nil)
        
        addSubview(placeHolderLabel)
        
        //手写代码自动布局
        placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 7))
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 5))
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: -10))
    }
    
    //通知监听文字的改变
    @objc private func textChange() {
        
        placeHolderLabel.isHidden = hasText
    }
    
    deinit {
        
    NotificationCenter.default.removeObserver(self)
    }

}
